package com.example.makerspace.service.impl;

import com.example.makerspace.dao.*;
import com.example.makerspace.domain.*;
import com.example.makerspace.dto.Result;
import com.example.makerspace.dto.TaskTagDTO;
import com.example.makerspace.service.PointBreakdownService;
import com.example.makerspace.utils.JwtUtils;
import com.example.makerspace.vo.TaskTagsVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PointBreakdownImpI implements PointBreakdownService {

    @Resource
    private PointBreakdownDAO pointBreakdownDAO;

    @Resource
    private SingInRecordDAO singInRecordDAO;

    @Resource
    private IntegralTasksDAO integralTasksDAO;

    @Resource
    private  MessageDAO messageDAO;

    @Resource
    private TaskTagDAO taskTagDAO;


    @Resource
    private  TaskFinishDAO taskFinishDAO;

    @Resource
    private  DemandDAO demandDAO;

    @Resource
    private UserDAO userDAO;

    private  static  final  Integer FirstPoint=2;

    private  static  final  Integer  MaxDay=14;


    private  static  final  String  SignType="连续签到";

    @Override
    public Result signIn(HttpServletRequest request) {
        String username = JwtUtils.getUsername(request);
        UserDO userDO = userDAO.selectByUsername(username);
        PointBreakdownDO pointBreakdownDO = new PointBreakdownDO();
        SingInRecordDO singInRecordDO = new SingInRecordDO();
        List<SingInRecordDO> singInRecordDOS = singInRecordDAO.selectByUserName(username);
        synchronized (this) {
            if (!CollectionUtils.isEmpty(singInRecordDOS)) {
                //判断今天是否进行了连续签到
                Date signDate = singInRecordDOS.get(0).getSignDate();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(signDate);
                calendar.add(Calendar.DAY_OF_YEAR, 1);
                signDate = calendar.getTime();
                Format f = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date();
                String format1 = f.format(signDate);
                String format = f.format(date);
                if (format1.equals(format)) {
                    if (singInRecordDOS.get(0).getContinueNumber() + 1 == MaxDay) {
                        singInRecordDOS.get(0).setContinueNumber(1);
                        singInRecordDOS.get(0).setSignDate(new Date());
                        singInRecordDOS.get(0).setIsSign(1);
                        //用户积分变化
                        userDO.setPoints(userDO.getPoints() + FirstPoint);
                        userDAO.updateById(userDO);
                        //签到记录表
                        singInRecordDAO.updateById(singInRecordDOS.get(0));
                        //积分明细
                        pointBreakdownDO.setType(SignType);
                        pointBreakdownDO.setUsername(username);
                        pointBreakdownDO.setDetails("连续签到" + singInRecordDOS.get(0).getContinueNumber() + "天" + ",获得" + FirstPoint + "积分");
                        pointBreakdownDO.setPoint("+" + FirstPoint);
                        pointBreakdownDAO.insert(pointBreakdownDO);
                    }
                    //为连续签到
                    singInRecordDOS.get(0).setContinueNumber(singInRecordDOS.get(0).getContinueNumber() + 1);
                    singInRecordDOS.get(0).setSignDate(new Date());
                    singInRecordDOS.get(0).setIsSign(1);
                    //用户积分变化
                    userDO.setPoints(userDO.getPoints() + FirstPoint);
                    userDAO.updateById(userDO);
                    //签到记录表
                    singInRecordDAO.updateById(singInRecordDOS.get(0));
                    //积分明细
                    pointBreakdownDO.setType(SignType);
                    pointBreakdownDO.setUsername(username);
                    pointBreakdownDO.setDetails("连续签到" + singInRecordDOS.get(0).getContinueNumber() + "天" + ",获得" + FirstPoint + "积分");
                    pointBreakdownDO.setPoint("+" + FirstPoint);
                    pointBreakdownDAO.insert(pointBreakdownDO);
                    return Result.success("连续签到成功!");
                }
                //断签的话
                userDO.setPoints(userDO.getPoints() + FirstPoint);
                userDAO.updateById(userDO);
                singInRecordDOS.get(0).setContinueNumber(1);
                singInRecordDOS.get(0).setSignDate(new Date());
                singInRecordDOS.get(0).setIsSign(1);
                singInRecordDAO.updateById(singInRecordDOS.get(0));
                pointBreakdownDO.setType(SignType);
                pointBreakdownDO.setUsername(username);
                pointBreakdownDO.setDetails("连续签到" + singInRecordDOS.get(0).getContinueNumber() + "天" + ",获得" + FirstPoint + "积分");
                pointBreakdownDO.setPoint("+" + FirstPoint);
                pointBreakdownDAO.insert(pointBreakdownDO);

                return Result.success("因为昨天您还没有签到,连续签到断了哦!");

            } else {
                singInRecordDO.setUsername(username);
                singInRecordDO.setSignDate(new Date());
                singInRecordDO.setIsSign(1);
                singInRecordDO.setContinueNumber(1);
                singInRecordDAO.insert(singInRecordDO);
                userDO.setPoints(userDO.getPoints() + FirstPoint);
                userDAO.updateById(userDO);
                pointBreakdownDO.setType(SignType);
                pointBreakdownDO.setUsername(username);
                pointBreakdownDO.setDetails("连续签到" + 1 + "天" + ",获得" + FirstPoint + "积分");
                pointBreakdownDO.setPoint("+" + FirstPoint);
                pointBreakdownDAO.insert(pointBreakdownDO);
                return Result.success("恭喜您,完成今日的签到！");
            }
        }
    }

    @Override
    public Result getPointsBreakdown(HttpServletRequest request) {
        String username = JwtUtils.getUsername(request);
        List<PointBreakdownDO> pointBreakdownDOS = pointBreakdownDAO.selectByUserName(username);
        return Result.success(pointBreakdownDOS);
    }

    @Override
    public Result getIntegralTasks(HttpServletRequest request) {
        String username = JwtUtils.getUsername(request);
        List<TaskTagsVO> taskTagsVOS = taskTagDAO.selectByJoin(username);
        return Result.success(taskTagsVOS);
    }

    @Override
    public Result getIfSameDay(HttpServletRequest request) {
        String username = JwtUtils.getUsername(request);
        List<SingInRecordDO> singInRecordDOS = singInRecordDAO.selectByUserName(username);
        LocalDate now = LocalDate.now();
        if(!CollectionUtils.isEmpty(singInRecordDOS)){
            Date signDate = singInRecordDOS.get(0).getSignDate();
            LocalDate localDate1= signDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            if(!now.isEqual(localDate1)){
                singInRecordDOS.get(0).setIsSign(0);
                singInRecordDAO.updateById(singInRecordDOS.get(0));
                return  Result.success("您可以签到啦");
            }
        }
        return  Result.success();
    }

    @Override
    public Result getSignIn(HttpServletRequest request) {
        String username = JwtUtils.getUsername(request);
        List<SingInRecordDO> singInRecordDOS = singInRecordDAO.selectByUserName(username);
        if(!CollectionUtils.isEmpty(singInRecordDOS)){
            return  Result.success(singInRecordDOS.get(0));
        }
        return  Result.success();
    }

    @Override
    public Result get() {
        List<DemandDO> demandDOS = demandDAO.selectAll();
        List<DemandDO> collect1 = demandDOS.stream().filter(item -> item.getIsShow().equals(1)).collect(Collectors.toList());
        List<String> collect = collect1.stream().map(item -> item.getUsername()).collect(Collectors.toList());

        List<String> listNew2 = new ArrayList<String>(new LinkedHashSet<String>(collect));
        for(String list:listNew2){
            MessageDO messageDO = new MessageDO();
            messageDO.setUsername(list);
            messageDO.setType(1);
            messageDO.setTitle("感谢信");
            messageDO.setContent("感谢参与赛博众创首次开放市场成果征集活动，截止目前第一批成果已审核完成，审核通过的产品已上架至开放市场，进入内部推介环节，敬请相关单位留意后续通知。第二批成果征集活动已经开启，欢迎各界先进技术成果参加，相关动态信息将通过赛博众创平台发布。");
            messageDAO.insert(messageDO);
        }
        System.out.println(listNew2);
        return  Result.success();
    }

    @Override
    public Result addTaskTag(TaskTagDTO taskTagDTO) {
        TaskTagDO taskTagDO = new TaskTagDO();
        BeanUtils.copyProperties(taskTagDTO,taskTagDO);
        taskTagDAO.insert(taskTagDO);
        List<TaskTagDO> taskTagDOS = taskTagDAO.selectAll();
        //获取最后一个
        TaskTagDO lastTaskTagDO = taskTagDOS.get(taskTagDOS.size()-1);
        List<UserDO> userDOS = userDAO.selectAll();
        List<UserDO> collect = userDOS.stream().filter(item -> !item.equals("admin")).collect(Collectors.toList());
        for(UserDO useDO:collect){
            TaskFinishDO taskFinishDO = new TaskFinishDO();
            taskFinishDO.setTaskId(lastTaskTagDO.getId());
            taskFinishDO.setUsername(useDO.getUsername());
            taskFinishDAO.insert(taskFinishDO);
        }
        return Result.success("新增标签成功!");
    }

    @Override
    public Result getTaskTag() {
        return Result.success(taskTagDAO.selectAll());
    }

    @Override
    public Result updateTaskTag(TaskTagDTO taskTagDTO) {
        TaskTagDO taskTagDO = new TaskTagDO();
        BeanUtils.copyProperties(taskTagDTO,taskTagDO);
        taskTagDAO.updateById(taskTagDO);
        return Result.success("更新成功!");
    }

    @Override
    public Result deleteTaskTag(Integer id) {
        taskTagDAO.deleteById(id);
        taskFinishDAO.deleteByTaskId(id);
        return Result.success("删除成功!");
    }
}

